<!--
 * @Author: fisher
 * @Date: 2024-01-02 17:39:01
 * @LastEditTime: 2024-04-26 14:27:05
 * @LastEditors: fisher luthor-li@qq.com
 * @Description: 
 * @FilePath: \front-end-template\src\modules\DataManage\tasks\modules\taskDetail.vue
-->
<template>
  <div class="taskDetail">
    <div ref="table" class="table">
      <fks-table
        ref="multipleTable"
        v-loading="tableLoading"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%; height: 100%; overflow-y: scroll"
        @selection-change="handleSelectionChange"
      >
        <fks-table-column type="selection" width="55" />
        <fks-table-column type="index" label="序号" width="50" />
        <fks-table-column prop="sourceName" label="源数据名称" width="200" />
        <fks-table-column prop="templateName" label="模板名称" show-overflow-tooltip />
        <fks-table-column prop="warehouseName" label="类型" width="200" />
        <fks-table-column prop="createDate" label="任务提交时间" width="200" />
        <fks-table-column prop="finishDate" label="任务完成时间" width="200" />
        <fks-table-column prop="keepTime" label="数据保留时间" width="200" />
        <fks-table-column prop="option" label="操作" width="200">
          <template slot-scope="scope">
            <fks-button v-if="scope.row.status == 3" type="primary" @click="downFile(scope.row)">
              下载
            </fks-button>
            <fks-button
              v-if="scope.row.status == 3"
              type="primary"
              @click="previewScene(scope.row)"
            >
              预览
            </fks-button>
          </template>
        </fks-table-column>
        <fks-table-column prop="status" label="状态" width="200">
          <template slot-scope="scope">
            <span @click="openLogs(scope.row)">{{ transStatusOption(scope.row.status) }}</span>
          </template>
        </fks-table-column>
      </fks-table>
    </div>
    <fks-pagination
      class="pagination"
      :current-page="pageNo"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { getTask, downloadRes } from '../api.js'
import { downloadWithProgress } from '../../utils/download.js'
export default {
  //import引入组件才能使用
  components: {},
  props: {
    searchData: {
      type: Object,
      default() {
        return {}
      }
    },
    searchParams: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      total: 0,
      pageSize: 10,
      pageNo: 1,
      tableLoading: false,
      tableData: [],
      // multipleSelection: [],
      timer: null,
      statusOptions: [
        {
          label: '无',
          value: ''
        },
        {
          label: '任务失败',
          value: '-1'
        },
        {
          label: '未开始',
          value: '0'
        },
        {
          label: '进行中',
          value: '1'
        },
        {
          label: '排队中',
          value: '2'
        },
        {
          label: '任务完成',
          value: '3'
        },
        {
          label: '任务取消',
          value: '4'
        }
      ],
      downloadNotify: {},
      progress: 0
    }
  },
  // 计算属性
  computed: {
    downloadProgress() {
      return this.$store.state.Download.downloadProgress
    },
    transStatusOption() {
      return (val) => {
        const target = this.statusOptions.find((item) => item.value == val)
        return target.label
      }
    }
  },
  // 监听data中的数据变化
  watch: {
    downloadProgress(val) {
      const dom = document.querySelector('#downloadProgress')
      const dom1 = document.querySelector('#downloadProgressText')
      this.progress = val
      if (dom) {
        dom.value = this.progress
        dom1.innerHTML = this.progress + '%'
      }
    }
  },
  // 生命周期，创建完成时（可以访问当前this实例）
  created() {},
  // 生命周期：挂载完成时（可以访问DOM元素）
  mounted() {
    console.log('this.', this)
    this.getData()
    this.timer = setInterval(() => {
      console.log('15s刷新数据！')
      this.getData()
    }, 30000)
  },
  beforeCreate() {}, //生命周期：创建之前
  beforeMount() {}, //生命周期：挂载之前
  beforeUpdate() {}, //生命周期：更新之前
  updated() {}, //生命周期：更新之后
  beforeDestroy() {
    console.log('i清理定时器')
    clearInterval(this.timer)
    this.timer = null
  }, //生命周期：销毁之前
  destroyed() {}, //生命周期：销毁完成
  activated() {},
  // 方法集合
  methods: {
    openLogs(val) {
      this.$emit('logs', val)
    },
    getData() {
      this.tableLoading = true
      const params = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        ...this.searchParams
      }
      const data = {
        ...this.searchData
      }
      getTask(params, data)
        .then((res) => {
          if (res.status) {
            const data = res.data
            console.log('tasks', data)
            this.total = data.total
            this.tableData = [...data.list]
          }
          this.tableLoading = false
        })
        .catch((err) => {
          throw new Error(err)
        })
    },
    handleSelectionChange(val) {
      // this.multipleSelection = val;
      this.$emit('multipleSelect', val)
    },
    downFile(val) {
      this.progress = 0
      let notifyDom = `<input type="range" id="downloadProgress" min='0' max='100' :value="${this.progress}">
                      <span id="downloadProgressText">${this.progress}%</span>
                       `
      this.downloadNotify = this.$notify({
        title: '下载文件',
        dangerouslyUseHTMLString: true,
        message: notifyDom,
        duration: 0
      })

      downloadWithProgress(val.outputPath).then((res) => {
        this.$message({
          message: '下载完成！',
          type: 'success'
        })
        if (res.status == 200) {
          const url = window.URL.createObjectURL(res.data)
          const link = document.createElement('a')
          link.style.display = 'none'
          link.setAttribute('href', url)
          link.setAttribute('download', val.outputPath + '.zip')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        }
        setTimeout(() => {
          this.downloadNotify.close()
        }, 1000)
      })

      // downloadRes(val.outputPath).then((res) => {
      //   console.log("downFile", res);
      //   if (res.status == 200) {
      //     const url = window.URL.createObjectURL(res.data);
      //     const link = document.createElement("a");
      //     link.style.display = "none";
      //     link.setAttribute("href", url);
      //     link.setAttribute("download", val.outputPath);
      //     document.body.appendChild(link);
      //     link.click();
      //     document.body.removeChild(link);
      //   }
      // });
    },
    previewScene() {
      this.$router.push({
        path: '/map'
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.pageNo = val
      this.getData()
    }
  }
}
</script>
<style lang="scss" scoped>
.table {
  height: calc(100% - 64px);
  overflow: hidden;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  padding: 20px 0;
}
</style>
